package com.yehui.alibaba.service.tcc.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.yehui.alibaba.dao.OrderDAO;
import com.yehui.alibaba.entity.OrderEntity;
import com.yehui.alibaba.service.tcc.TCCOrderService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author 业徽
 * @date 2021/8/5
 */
@Service("tCCOrderService")
public class TCCOrderServiceImpl implements TCCOrderService {

    private static final Logger logger = LoggerFactory.getLogger(TCCOrderServiceImpl.class);

    @Resource
    private OrderDAO orderDao;

    /**
     * 入库
     *
     * @param userId
     * @param productId
     * @param amount
     * @return
     */
    @Override
    @DS(value = "order-ds")
    @Transactional(propagation = Propagation.REQUIRES_NEW) // 开启新事物
    public Integer add(BusinessActionContext actionContext, Long userId, Long productId, Integer amount) {
        // 保存订单
        OrderEntity order = new OrderEntity().setUserId(userId).setProductId(productId).setPayAmount(amount);
        orderDao.saveOrder(order);
        logger.info("[createOrder] 保存订单: {}", order.getId());
        // 返回订单编号
        return order.getId();
    }

    /**
     * Commit boolean.
     *
     * @param actionContext the action context
     * @return the boolean
     */
    @Override
    public boolean tccCommit(BusinessActionContext actionContext) {
        logger.info("tcc 提交. txId={}, context={}", RootContext.getXID(), actionContext);
        return true;
    }

    /**
     * Rollback boolean.
     *
     * @param actionContext the action context
     * @return the boolean
     */
    @Override
    public boolean tccRollback(BusinessActionContext actionContext) {
        logger.info("tcc 回滚. txId={}, context={}", RootContext.getXID(), actionContext);
        return true;
    }
}
